package com.resou.reader.bookshelf.bookedit;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.resou.reader.MainActivity;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.bookshelf.bookedit.adapter.BookShelfEditAdapter;
import com.resou.reader.bookshelf.bookedit.adapter.BookShelfListEditAdapter;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.utils.DialogUtil;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.PreferenceUtil;

import com.resou.reader.utils.ToastUtil;

import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BookShelfEditActivity extends ResouBaseActivity<BookShelfEditPresenter> implements IBookShelfEditView, BookShelfEditAdapter.OnItemSelectedListener, BookShelfListEditAdapter.OnItemSelectedListener {

    @BindView(R.id.shelf_edit_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_right_btn)
    TextView tvRightBtn;
    @BindView(R.id.btn_delete)
    Button btnDelete;
    public boolean isInEditMode = true;
    @BindView(R.id.no_book_layout)
    LinearLayout noBookLayout;
    @BindView(R.id.shelf_edit_recycler_list)
    RecyclerView shelfEditRecyclerList;
    @BindView(R.id.tvGobook)
    TextView tvGobook;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    private BookShelfEditAdapter mAdapter;
    private BookShelfListEditAdapter mListAdapter;
    private QMUITipDialog mLoadingDialog;
    private boolean isListShow = PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).getIsListShow();
    int selectedCount = 0;
    int position = -1;
    private  DialogUtil mDialogUtil;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, BookShelfEditActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initStatusBar() {
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        }
        toolbar.setBackgroundColor(getResources().getColor(R.color.white));
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
            actionBar.setDisplayShowTitleEnabled(false);
        }
        tvTitle.setText("批量管理");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_book_shelf_edit;
    }

    @Override
    public void retryRefreshData() {
        showLoading();
        mPresenter.requestPursuitBookList();
    }

    @Override
    protected void initPresenter() {
        mPresenter = new BookShelfEditPresenter(this);
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        position = intent.getIntExtra("position", -1);
        mListAdapter = new BookShelfListEditAdapter(this);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        shelfEditRecyclerList.setLayoutManager(linearLayoutManager1);
        shelfEditRecyclerList.setAdapter(mListAdapter);

        mAdapter = new BookShelfEditAdapter(this);
        LinearLayoutManager linearLayoutManager2 = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(linearLayoutManager2);
        mRecyclerView.setAdapter(mAdapter);


        btnDelete.setTextColor(Color.parseColor("#ff999999"));
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedCount == 0) {
                    Toast.makeText(BookShelfEditActivity.this, "请选择删除的书籍", Toast.LENGTH_SHORT).show();
                }
            }
        });

        tvGobook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.instance != null) {
                    MainActivity.instance.setTabSelection(1);
                    finish();
                }
            }
        });

        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        if (position != -1) {
            mAdapter.setPosition(position);
            mListAdapter.setPosition(position);
            selectedCount = 1;
            btnDelete.setTextColor(getResources().getColor(R.color.colorAccent));
            btnDelete.setText("删除(已选" + selectedCount + "项)");
            btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!NetworkUtils.isNetworkConnected(BookShelfEditActivity.this)) {
                        ToastUtil.makeShortToast("网络异常");
                        return;
                    }
                    if(mDialogUtil == null) {
                        mDialogUtil = new DialogUtil(BookShelfEditActivity.this);
                    }
                    mDialogUtil.showDialog("删除所选书籍？", "取消", "确定", null, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (isListShow) {
                                mListAdapter.deleteSelectedItems();
                            } else {
                                mAdapter.deleteSelectedItems();
                            }
                            onItemSelected();
                        }
                    }, true);
                }
            });
            shelfEditRecyclerList.scrollToPosition(position);
        }
    }

    /**
     * RecyclerView 移动到当前位置，
     *
     * @param manager       设置RecyclerView对应的manager
     * @param mRecyclerView 当前的RecyclerView
     * @param n             要跳转的位置
     */
    public void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {
        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();

        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }
    }


    @OnClick({R.id.tv_right_btn})
    public void onClick(View view) {
        if (view == tvRightBtn) {
            if (isListShow) {
                if (!isInEditMode) {
                    //如果不处于编辑模式下
                    startEditMode();
                } else {
                    //处于编辑模式下
                    if (mListAdapter.isSelectedAll()) {
                        /**
                         * 判断先前状态
                         */
                        if (tvRightBtn.getText().toString().equals("全不选")) {
                            position = -1;
                            //已经全选，则反选
                            mListAdapter.setSelectedAll(false);
                            tvRightBtn.setText("全选");
                        } else {
                            //已经全选，则反选
                            mListAdapter.setSelectedAll(true);
                            tvRightBtn.setText("全不选");
                        }

                    } else {
                        /**
                         * 判断先前状态
                         */
                        if (tvRightBtn.getText().toString().equals("全选")) {
                            mListAdapter.setSelectedAll(true);
                            tvRightBtn.setText("全不选");
                        } else {
                            mListAdapter.setSelectedAll(false);
                            tvRightBtn.setText("全选");
                        }

                    }
                    onItemSelected();
                }
            } else {
                if (!isInEditMode) {
                    //如果不处于编辑模式下
                    startEditMode();
                } else {
                    //处于编辑模式下
                    if (mAdapter.isSelectedAll()) {
                        /**
                         * 判断先前状态
                         */
                        if (tvRightBtn.getText().toString().equals("全不选")) {
                            //已经全选，则反选
                            mAdapter.setSelectedAll(false);
                            tvRightBtn.setText("全选");
                        } else {
                            //已经全选，则反选
                            mAdapter.setSelectedAll(true);
                            tvRightBtn.setText("全不选");
                        }

                    } else {
                        /**
                         * 判断先前状态
                         */
                        if (tvRightBtn.getText().toString().equals("全选")) {
                            mAdapter.setSelectedAll(true);
                            tvRightBtn.setText("全不选");
                        } else {
                            mAdapter.setSelectedAll(false);
                            tvRightBtn.setText("全选");
                        }

                    }
                    onItemSelected();
                }
            }
        }
    }

    private void startEditMode() {
        isInEditMode = true;
        tvRightBtn.setText("全选");
        if (isListShow) {
            mListAdapter.notifyDataSetChanged();
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void initData() {
        showLoading();
        mPresenter.requestPursuitBookList();
    }

    @Override
    public void showContent() {
        dissLoading();
    }

    @Override
    public void showProgress() {
        mLoadingDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("删除中")
                .create();
        mLoadingDialog.show();
    }

    @Override
    public void showError(Throwable throwable) {
        dissLoading();
        ToastUtil.makeShortToast("网络异常");
        showNetErrorView(R.id.rlContent);
    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void setBookList(List<BookCollection> bookList) {
        if (bookList.size() > 0) {
            if (isListShow) {
                mListAdapter.setBookList(bookList);
                shelfEditRecyclerList.setVisibility(View.VISIBLE);
                mRecyclerView.setVisibility(View.GONE);
            } else {
                mAdapter.setBookList(bookList);
                mRecyclerView.setVisibility(View.VISIBLE);
                shelfEditRecyclerList.setVisibility(View.GONE);
            }
            tvRightBtn.setText("全选");
            btnDelete.setVisibility(View.VISIBLE);
            tvRightBtn.setVisibility(View.VISIBLE);
            tvRightBtn.setAlpha(1);
            tvRightBtn.setClickable(true);
            noBookLayout.setVisibility(View.GONE);
        } else {
            btnDelete.setVisibility(View.GONE);
            tvRightBtn.setVisibility(View.GONE);
            tvRightBtn.setAlpha(0.7f);
            tvRightBtn.setClickable(false);
            mRecyclerView.setVisibility(View.GONE);
            shelfEditRecyclerList.setVisibility(View.GONE);
            noBookLayout.setVisibility(View.VISIBLE);
        }

    }

    private static final String TAG = "BookShelfvity-App";

    @Override
    public void showSuccess() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
            mDialogUtil.cancelDialog();
            Log.d(TAG, "showSuccess: ");
        }
        QMUITipDialog dialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                .setTipWord("删除成功")
                .create();
        dialog.show();
        new Handler().postDelayed(dialog::dismiss, 800);
    }

    @Override
    public void showFailed() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        QMUITipDialog dialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                .setTipWord("删除失败")
                .create();
        dialog.show();
        new Handler().postDelayed(dialog::dismiss, 800);
    }

    @Override
    public void onItemSelected() {
        if (isListShow) {
            selectedCount = mListAdapter.getSelectedItemCount();
        } else {
            selectedCount = mAdapter.getSelectedItemCount();
        }

        if (selectedCount == 0) {
            btnDelete.setText("删除");
            btnDelete.setTextColor(Color.parseColor("#ff999999"));
            btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(BookShelfEditActivity.this, "请选择删除的书籍", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            btnDelete.setTextColor(getResources().getColor(R.color.colorAccent));
            btnDelete.setText("删除(已选" + selectedCount + "项)");
            btnDelete.setTextColor(Color.parseColor("#ffd53d2d"));
            btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!NetworkUtils.isNetworkConnected(BookShelfEditActivity.this)) {
                        ToastUtil.makeShortToast("网络异常");
                        return;
                    }
                    if(mDialogUtil == null) {
                        mDialogUtil = new DialogUtil(BookShelfEditActivity.this);
                    }
                    mDialogUtil.showDialog("删除所选书籍？", "取消", "确定", null, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (isListShow) {
                                mListAdapter.deleteSelectedItems();
                            } else {
                                mAdapter.deleteSelectedItems();
                            }
                            onItemSelected();
                        }
                    }, true);
                }
            });
        }

        if (isListShow) {
            if (mListAdapter.getItemCount() == 0) {
                tvRightBtn.setVisibility(View.GONE);
                tvRightBtn.setText("全选");
                tvRightBtn.setAlpha(0.7f);
                tvRightBtn.setClickable(false);
                mRecyclerView.setVisibility(View.GONE);
                btnDelete.setVisibility(View.GONE);
                noBookLayout.setVisibility(View.VISIBLE);
            } else {
                tvRightBtn.setClickable(true);
                tvRightBtn.setAlpha(1);
                btnDelete.setVisibility(View.VISIBLE);
                mRecyclerView.setVisibility(View.VISIBLE);
                noBookLayout.setVisibility(View.GONE);
                if (mListAdapter.getItemCount() != selectedCount) {
                    tvRightBtn.setText("全选");
                } else {
                    tvRightBtn.setText("全不选");
                }
            }
        } else {
            if (mAdapter.getItemCount() == 0) {
                tvRightBtn.setVisibility(View.GONE);
                tvRightBtn.setText("全选");
                tvRightBtn.setAlpha(0.7f);
                tvRightBtn.setClickable(false);
                mRecyclerView.setVisibility(View.GONE);
                btnDelete.setVisibility(View.GONE);
                noBookLayout.setVisibility(View.VISIBLE);
            } else {
                tvRightBtn.setClickable(true);
                tvRightBtn.setAlpha(1);
                btnDelete.setVisibility(View.VISIBLE);
                mRecyclerView.setVisibility(View.VISIBLE);
                noBookLayout.setVisibility(View.GONE);
                if (mAdapter.getItemCount() != selectedCount) {
                    tvRightBtn.setText("全选");
                } else {
                    tvRightBtn.setText("全不选");
                }
            }
        }
    }

    @Override
    public void onItemDeleted(BookCollection collection) {
        mPresenter.delete(collection);
    }

    @Override
    public void onItemsDeleted(Set<BookCollection> collections) {
        mPresenter.deleteAll(collections);
        onItemSelected();
    }

    @Override
    public void onItemClicked(BookCollection collection) {
//        BookDetailActivity.startDetailActivity(this, collection.getBookId());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDialogUtil!= null) {
            mDialogUtil.cancelDialog();
            mDialogUtil = null;
        }
    }
}
